package fr.afcepf.ai90.venteenligne.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.sql.DataSource;

import fr.afcepf.ai90.venteenligne.datasource.SimpleDataSource;
import fr.afcepf.ai90.venteenligne.entity.Commande;
import fr.afcepf.ai90.venteenligne.entity.Personne;

public class DataCommande implements IDataCommande {

	private String reqCreationCommande = 
			"INSERT INTO commande(date_commande,id_personne) VALUES (?, ?)";
	private int indiceParamDateCommande = 1;
	private int indiceParamIdPersonne = 2;
	private final String colonneNumero = "numero";
	private final String colonneDateCommande = "date_commande";
	private final String colonneIdPersonne = "id_personne";

	/**
	 * @return the reqCreationCommande
	 */
	public String getReqCreationCommande() {
		return reqCreationCommande;
	}


	/**
	 * @param reqCreationCommande the reqCreationCommande to set
	 */
	public void setReqCreationCommande(String reqCreationCommande) {
		this.reqCreationCommande = reqCreationCommande;
	}


	@Override
	public Integer creationCommande(Commande cmd) {
		DataSource dc = new SimpleDataSource();
        Integer retour = null;
        Connection cnx;
        

        try {
             cnx = dc.getConnection();
            PreparedStatement pstmt = cnx.prepareStatement(reqCreationCommande,Statement.RETURN_GENERATED_KEYS);
            pstmt.setDate(indiceParamDateCommande, new java.sql.Date(cmd.getDateCommande().getTime()));
            //construction de la date a partir du datestamp donc recupere la date en millisecondes
            pstmt.setInt(indiceParamIdPersonne, cmd.getPersonne().getId());
            pstmt.executeUpdate();
            ResultSet rs = pstmt.getGeneratedKeys();
            if(rs.next()){
                retour = rs.getInt(1);
            }
            rs.close();
            pstmt.close();
            cnx.close();

        } catch (SQLException  | NullPointerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		return retour;
	}

}
